package logic;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import operators.Move;
import environment.Environment;
import environment.Environment.Destination;
import es.deusto.ingenieria.is.formulation.Problem;
import es.deusto.ingenieria.is.formulation.State;
import es.deusto.ingenieria.is.search.Node;
import es.deusto.ingenieria.is.search.SearchMethod;

public class IndyProblem extends Problem {

	protected void createOperators() {
		super.addOperator(new Move(Destination.UP));
		super.addOperator(new Move(Destination.DOWN));
		super.addOperator(new Move(Destination.LEFT));
		super.addOperator(new Move(Destination.RIGHT));
	}

	public boolean isFinalState(State state) {
		if (state != null) {
			Environment environment = (Environment) state.getInformation();
			return environment.getGoalCell().equals(
					environment.getIndy().getLocation());
		} else {
			return false;
		}
	}

	public void solve(SearchMethod searchMethod) {
		Thread t = new Thread();
		int totalMovements = 0;
		for (int i = 0; i < 5; i++) {
			try {
				t.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
			System.out.println("\n* Begin '"
					+ searchMethod.getClass().getCanonicalName()
					+ "' ("
					+ formatter.format(GregorianCalendar.getInstance()
							.getTime()) + ")");
			Node finalNode = searchMethod.search(this, this.getInitialStates()
					.get(i));
			System.out.println("* End '"
					+ searchMethod.getClass().getCanonicalName()
					+ "' ("
					+ formatter.format(GregorianCalendar.getInstance()
							.getTime()) + ")");

			if (finalNode != null) {
				List<String> operators = new ArrayList<String>();
				searchMethod.solutionPath(finalNode, operators);
				searchMethod.createSolutionLog(operators);
				System.out.println("* Solution found!!");
				System.out.println("  * Movements: " + finalNode.getDepth());
				totalMovements += finalNode.getDepth();
				System.out.println("  * Total Movements: " + totalMovements);
				System.out.println((Environment)finalNode.getState().getInformation());
			} else {
				System.out.println("* Solution not found :-(");
			}
			((Environment)finalNode.getState().getInformation()).setGoalAsNearestGem();
			this.addInitialState(finalNode.getState());
		}
	}
}
